// 模拟阿里云短信服务的后端服务器
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// 存储验证码的临时数据库
const verificationCodes = {};

// 发送短信验证码接口
app.post('/api/send-sms-code', (req, res) => {
  const { phoneNumber } = req.body;
  
  if (!phoneNumber || !/^1[3-9]\d{9}$/.test(phoneNumber)) {
    return res.json({
      success: false,
      message: '无效的手机号码'
    });
  }

  // 生成6位随机验证码
  const code = Math.floor(100000 + Math.random() * 900000).toString();
  
  // 存储验证码（实际生产环境会通过阿里云SDK发送短信）
  verificationCodes[phoneNumber] = {
    code,
    expireAt: Date.now() + 5 * 60 * 1000  // 5分钟有效期
  };
  
  console.log(`为手机号 ${phoneNumber} 生成验证码: ${code}`);
  
  return res.json({
    success: true,
    message: '验证码已发送'
  });
});

// 验证短信验证码接口
app.post('/api/verify-sms-code', (req, res) => {
  const { phoneNumber, code } = req.body;
  
  if (!phoneNumber || !code) {
    return res.json({
      success: false,
      message: '手机号和验证码不能为空'
    });
  }

  const storedVerification = verificationCodes[phoneNumber];
  
  if (!storedVerification) {
    return res.json({
      success: false,
      message: '验证码不存在或已过期，请重新获取'
    });
  }
  
  if (Date.now() > storedVerification.expireAt) {
    delete verificationCodes[phoneNumber];
    return res.json({
      success: false,
      message: '验证码已过期，请重新获取'
    });
  }
  
  if (storedVerification.code !== code) {
    return res.json({
      success: false,
      message: '验证码错误'
    });
  }
  
  // 验证成功后清除验证码
  delete verificationCodes[phoneNumber];
  
  return res.json({
    success: true,
    message: '验证成功'
  });
});

const PORT = process.env.PORT || 3010;

app.listen(PORT, () => {
  console.log(`模拟阿里云短信服务器运行在 http://localhost:${PORT}`);
}); 